package com.lin.controller.client;

import com.github.pagehelper.PageInfo;
import com.lin.entity.Article;
import com.lin.entity.Comment;
import com.lin.service.ArticleService;
import com.lin.service.CommentService;
import com.lin.service.StatisticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 阿林
 */
@Controller
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private StatisticService statisticService;

    /**
     * 启动程序, 进入首页
     *
     * @param request
     * @return
     */
    @RequestMapping("/")
    public String index(HttpServletRequest request) {
        return page(request, 1, 5);
    }


    /**
     * 处理首页 分页请求 --通用的分页数据获取
     *
     * @param request
     * @param pageNum
     * @param count
     * @return
     */
    @RequestMapping("/page/{pageNum}")
    public String page(HttpServletRequest request, @PathVariable("pageNum") Integer pageNum, @RequestParam(value = "count", defaultValue = "5") Integer count) {
        // 当前第几页  ,每页显示多少条数据
        //数据准备
        //1 文章分页数据
        PageInfo<Article> articles = articleService.findArticleWithPage(pageNum, count);
        //2 阅读排行榜 :根据点击量
        List<Article> articleList = articleService.getHeatArticles();
        //保存到request域中
        //分页信息
        request.setAttribute("articles", articles);
        //排行榜信息
        request.setAttribute("articleList", articleList);
        /* request.setAttribute("commons", new Commons());*/
        return "client/index";
    }

    /**
     * 进入详情页
     *
     * @param request
     * @param articleId
     * @param cp
     * @param count
     * @return
     */
    @RequestMapping("/articleDetail/{articleId}")
    public String articleDetail(HttpServletRequest request, @PathVariable("articleId") Integer articleId, @RequestParam(value = "cp", defaultValue = "1") Integer cp, @RequestParam(value = "count", defaultValue = "5") Integer count) {
        //文章数据
        Article article = articleService.findById(articleId);
        //文章评论数据
        PageInfo<Comment> comments = commentService.findByArticleId(articleId, cp, count);
        request.setAttribute("article", article);
        request.setAttribute("comments", comments);
        /*   request.setAttribute("commons", new Commons());*/
        //更新文章点击量
        //文章点击量在原有的基础上加 1
        statisticService.updateHits(articleId);

        return "client/articleDetails";
    }
}
